<template>
	<view class="container">
		<!-- 顶部信息 -->
		<view class="header">
			<text class="title">区域选择</text>
			<text class="desc">请先选择针头区域，再选择水滴区域</text>
		</view>
		
		<!-- 状态指示 -->
		<view class="status-bar">
			<view class="status-step" :class="{'active': currentStep === 'needle', 'completed': needleRegionSelected}">
				<view class="step-indicator needle-color">1</view>
				<text class="step-text">针头区域</text>
				<view class="step-check" v-if="needleRegionSelected">✓</view>
			</view>
			<view class="step-connector"></view>
			<view class="status-step" :class="{'active': currentStep === 'drop', 'completed': dropRegionSelected}">
				<view class="step-indicator drop-color">2</view>
				<text class="step-text">水滴区域</text>
				<view class="step-check" v-if="dropRegionSelected">✓</view>
			</view>
		</view>
		
		<!-- 选择按钮 -->
		<view class="selection-buttons">
			<button 
				class="selection-btn" 
				:class="{'active': currentStep === 'needle', 'completed': needleRegionSelected}"
				@click="switchToNeedleStep">
				<text class="btn-text">选择针头</text>
			</button>
			
			<button 
				class="selection-btn" 
				:class="{'active': currentStep === 'drop', 'completed': dropRegionSelected}"
				@click="switchToDropStep">
				<text class="btn-text">选择水滴</text>
			</button>
		</view>
		
		<!-- 区域选择器 - 改用canvas直接实现框选 -->
		<view class="selector-container">
			<view class="canvas-container">
				<canvas 
					:style="{width: width+'px', height: height+'px', backgroundImage: 'url(' + imageSrc + ')', backgroundRepeat: 'no-repeat', backgroundSize: '100% 100%'}" 
					canvas-id="regionCanvas" 
					@touchstart="startDrawing" 
					@touchmove="drawing" 
					@touchend="endDrawing">
				</canvas>
			</view>
		</view>
		
		<!-- 操作说明 -->
		<view class="instruction">
			<view class="instruction-icon">💡</view>
			<view class="instruction-text">
				<text v-if="currentStep === 'drop'">请在图片上拖动选择水滴区域。确保包含整个水滴，但不要太大。</text>
				<text v-else-if="currentStep === 'needle'">请在图片上拖动选择针头区域。尽量精确地选择针头末端部分。</text>
			</view>
		</view>
		
		<!-- 底部按钮 -->
		<view class="action-buttons">
			<button class="action-btn reset-btn" @click="resetCurrentRegion">
				<text class="btn-text">重置当前选区</text>
			</button>
			
			<button v-if="currentStep === 'drop'" 
					class="action-btn next-btn" 
					:disabled="!dropRegionSelected"
					:class="{'disabled-btn': !dropRegionSelected}"
					@click="goToNeedleStep">
				<text class="btn-text">下一步</text>
			</button>
			
			<button v-else-if="currentStep === 'needle'" 
					class="action-btn prev-btn" 
					@click="goToDropStep">
				<text class="btn-text">上一步</text>
			</button>
			
			<button v-if="currentStep === 'needle'" 
					class="action-btn confirm-btn" 
					:disabled="!needleRegionSelected"
					:class="{'disabled-btn': !needleRegionSelected}"
					@click="confirmRegions">
				<text class="btn-text">确认并计算</text>
			</button>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';

// 图片和画布相关
const imageSrc = ref('');
const ctx = ref(null);
const width = ref(0);
const height = ref(0);
const imgWidth = ref(0);
const imgHeight = ref(0);
const proportion = ref(1);

// 绘制相关
const isDrawing = ref(false);
const startPoint = ref({ x: 0, y: 0 });
const currentRect = ref(null);

// 步骤控制
const currentStep = ref('drop'); // 'drop' 或 'needle'

// 区域数据
const dropRegion = ref([[0, 0], [0, 0]]);
const needleRegion = ref([[0, 0], [0, 0]]);

// 判断是否选择了区域
const dropRegionSelected = computed(() => {
	return isValidRegion(dropRegion.value);
});

const needleRegionSelected = computed(() => {
	return isValidRegion(needleRegion.value);
});

// 初始化画布和图片
const initCanvas = () => {
	ctx.value = uni.createCanvasContext('regionCanvas', this);
	
	// 设置绘制样式
	if (currentStep.value === 'drop') {
		ctx.value.setStrokeStyle('#1890ff'); // 蓝色表示水滴区域
	} else {
		ctx.value.setStrokeStyle('#ff4d4f'); // 红色表示针头区域
	}
	ctx.value.setLineWidth(2);
	
	// 绘制已存在的区域
	drawExistingRegions();
}

// 获取图片信息并设置画布大小
const getImageInfo = () => {
	if (!imageSrc.value) return;
	
	uni.showLoading({ title: '加载图片中...' });
	
	uni.getImageInfo({
		src: imageSrc.value,
		success: (res) => {
			imgWidth.value = res.width;
			imgHeight.value = res.height;
			calculateCanvasSize();
			
			// 初始化完成后隐藏加载提示
			uni.hideLoading();
		},
		fail: (err) => {
			console.error('获取图片信息失败:', err);
			uni.hideLoading();
			
			uni.showToast({
				title: '加载图片失败',
				icon: 'none'
			});
		}
	});
}

// 根据图片尺寸和屏幕计算画布大小
const calculateCanvasSize = () => {
	const systemInfo = uni.getSystemInfoSync();
	const screenWidth = systemInfo.windowWidth;
	const screenHeight = systemInfo.windowHeight * 0.6; // 画布高度约为屏幕高度的60%
	
	const imageRatio = imgWidth.value / imgHeight.value;
	
	if (imageRatio > 1) {
		// 宽图片
		width.value = screenWidth - 40; // 留出边距
		height.value = width.value / imageRatio;
		
		// 如果高度超出了限制，则调整宽度
		if (height.value > screenHeight) {
			height.value = screenHeight;
			width.value = height.value * imageRatio;
		}
	} else {
		// 高图片
		height.value = screenHeight;
		width.value = height.value * imageRatio;
		
		// 如果宽度超出了限制，则调整高度
		if (width.value > screenWidth - 40) {
			width.value = screenWidth - 40;
			height.value = width.value / imageRatio;
		}
	}
	
	// 计算比例用于坐标转换
	proportion.value = width.value / imgWidth.value;
	
	console.log('画布尺寸:', width.value, 'x', height.value);
	console.log('图片尺寸:', imgWidth.value, 'x', imgHeight.value);
	console.log('比例:', proportion.value);
	
	// 更新画布和重新绘制
	setTimeout(() => {
		initCanvas();
	}, 300);
}

// 绘制已存在的区域
const drawExistingRegions = () => {
	// 清除画布
	ctx.value.clearRect(0, 0, width.value, height.value);
	
	// 绘制水滴区域（蓝色）
	if (isValidRegion(dropRegion.value)) {
		ctx.value.setStrokeStyle('#1890ff');
		const [start, end] = dropRegion.value;
		const x = start[0] * proportion.value;
		const y = start[1] * proportion.value;
		const w = (end[0] - start[0]) * proportion.value;
		const h = (end[1] - start[1]) * proportion.value;
		
		ctx.value.beginPath();
		ctx.value.rect(x, y, w, h);
		ctx.value.stroke();
	}
	
	// 绘制针头区域（红色）
	if (isValidRegion(needleRegion.value)) {
		ctx.value.setStrokeStyle('#ff4d4f');
		const [start, end] = needleRegion.value;
		const x = start[0] * proportion.value;
		const y = start[1] * proportion.value;
		const w = (end[0] - start[0]) * proportion.value;
		const h = (end[1] - start[1]) * proportion.value;
		
		ctx.value.beginPath();
		ctx.value.rect(x, y, w, h);
		ctx.value.stroke();
	}
	
	// 提交绘制
	ctx.value.draw();
}

// 开始绘制选区
const startDrawing = (e) => {
	isDrawing.value = true;
	
	const touch = e.changedTouches[0];
	startPoint.value = {
		x: touch.x,
		y: touch.y
	};
	
	// 清除画布并重新绘制已有区域
	drawExistingRegions();
}

// 绘制过程
const drawing = (e) => {
	if (!isDrawing.value) return;
	
	const touch = e.changedTouches[0];
	const currentX = touch.x;
	const currentY = touch.y;
	
	// 计算矩形的位置和大小
	const rectX = Math.min(startPoint.value.x, currentX);
	const rectY = Math.min(startPoint.value.y, currentY);
	const rectWidth = Math.abs(currentX - startPoint.value.x);
	const rectHeight = Math.abs(currentY - startPoint.value.y);
	
	// 保存当前矩形
	currentRect.value = {
		x: rectX,
		y: rectY,
		width: rectWidth,
		height: rectHeight
	};
	
	// 清除画布并重新绘制
	ctx.value.clearRect(0, 0, width.value, height.value);
	drawExistingRegions();
	
	// 设置当前选取的样式
	if (currentStep.value === 'drop') {
		ctx.value.setStrokeStyle('#1890ff'); // 蓝色表示水滴区域
	} else {
		ctx.value.setStrokeStyle('#ff4d4f'); // 红色表示针头区域
	}
	ctx.value.setLineWidth(2);
	
	// 绘制当前矩形
	ctx.value.beginPath();
	ctx.value.rect(rectX, rectY, rectWidth, rectHeight);
	ctx.value.stroke();
	ctx.value.draw();
}

// 结束绘制
const endDrawing = () => {
	if (!isDrawing.value || !currentRect.value) return;
	isDrawing.value = false;
	
	// 将画布坐标转换回实际图片坐标
	const startX = Math.round(currentRect.value.x / proportion.value);
	const startY = Math.round(currentRect.value.y / proportion.value);
	const endX = Math.round((currentRect.value.x + currentRect.value.width) / proportion.value);
	const endY = Math.round((currentRect.value.y + currentRect.value.height) / proportion.value);
	
	// 更新对应的区域
	if (currentStep.value === 'drop') {
		dropRegion.value = [[startX, startY], [endX, endY]];
	} else {
		needleRegion.value = [[startX, startY], [endX, endY]];
	}
	
	// 清除当前矩形
	currentRect.value = null;
	
	// 重新绘制
	drawExistingRegions();
}

// 验证区域是否有效
const isValidRegion = (region) => {
	if (!region || !region[0] || !region[1]) return false;
	
	const width = Math.abs(region[1][0] - region[0][0]);
	const height = Math.abs(region[1][1] - region[0][1]);
	
	// 区域至少要有一定大小才算有效
	return width > 10 && height > 10;
};

// 页面加载时检查传入的图片
onMounted(() => {
	// 显示加载中
	uni.showLoading({
		title: '加载图片中...',
		mask: true
	})
	
	// 从缓存获取图片路径
	const analyzedImagePath = uni.getStorageSync('analyzedImagePath');
	if (analyzedImagePath) {
		imageSrc.value = analyzedImagePath;
		console.log('区域选择页面接收到图片路径:', analyzedImagePath);
		
		// 从缓存获取默认区域设置
		const defaultDropRegion = uni.getStorageSync('defaultDropRegion');
		const defaultNeedleRegion = uni.getStorageSync('defaultNeedleRegion');
		
		if (defaultDropRegion && Array.isArray(defaultDropRegion) && defaultDropRegion.length === 2) {
			dropRegion.value = defaultDropRegion;
			console.log('加载默认水滴区域:', defaultDropRegion);
		}
		
		if (defaultNeedleRegion && Array.isArray(defaultNeedleRegion) && defaultNeedleRegion.length === 2) {
			needleRegion.value = defaultNeedleRegion;
			console.log('加载默认针头区域:', defaultNeedleRegion);
		}
		
		// 默认进入针头选择模式
		currentStep.value = 'needle';
		
		// 初始化画布和获取图片信息
		setTimeout(() => {
			getImageInfo();
		}, 500);
	} else {
		// 隐藏加载提示
		uni.hideLoading();
		
		// 如果没有图片，提示并返回
		uni.showToast({
			title: '没有可选择的图片',
			icon: 'none',
			complete: () => {
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		});
	}
});

// 切换到针头选择
const switchToNeedleStep = () => {
	currentStep.value = 'needle';
	initCanvas();
};

// 切换到水滴选择
const switchToDropStep = () => {
	// 检查是否已完成针头选择
	if (!needleRegionSelected.value) {
		uni.showToast({
			title: '请先完成针头区域选择',
			icon: 'none'
		});
		return;
	}
	
	currentStep.value = 'drop';
	initCanvas();
};

// 重置当前选区
const resetCurrentRegion = () => {
	if (currentStep.value === 'drop') {
		dropRegion.value = [[0, 0], [0, 0]];
	} else {
		needleRegion.value = [[0, 0], [0, 0]];
	}
	
	// 重新绘制
	drawExistingRegions();
};

// 进入针头选择步骤
const goToNeedleStep = () => {
	currentStep.value = 'needle';
	
	// 更新画笔颜色并重新绘制
	initCanvas();
};

// 进入水滴选择步骤
const goToDropStep = () => {
	if (!needleRegionSelected.value) {
		uni.showToast({
			title: '请先选择针头区域',
			icon: 'none'
		});
		return;
	}
	
	currentStep.value = 'drop';
	
	// 更新画笔颜色并重新绘制
	initCanvas();
};

// 确认区域并返回
const confirmRegions = () => {
	if (!dropRegionSelected.value || !needleRegionSelected.value) {
		uni.showToast({
			title: '请完成所有区域选择',
			icon: 'none'
		});
		return;
	}
	
	// 显示加载中提示
	uni.showLoading({
		title: '保存区域中...',
		mask: true
	});
	
	// 保存选定的区域到存储
	uni.setStorageSync('selectedDropRegion', dropRegion.value);
	uni.setStorageSync('selectedNeedleRegion', needleRegion.value);
	
	// 延迟执行，避免闪烁
	setTimeout(() => {
		uni.hideLoading();
		
		// 返回到上一页
		uni.navigateBack({
			animationType: 'slide-out-right', // 使用向右滑出动画
			animationDuration: 300, // 设置动画时长
			success: () => {
				// 发送事件通知上一页更新
				uni.$emit('regionsSelected', {
					dropRegion: dropRegion.value,
					needleRegion: needleRegion.value
				});
				
				// 清除默认区域设置，避免影响下次使用
				uni.removeStorageSync('defaultDropRegion');
				uni.removeStorageSync('defaultNeedleRegion');
			}
		});
	}, 300);
};
</script>

<style>
.container {
	display: flex;
	flex-direction: column;
	padding: 20rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
}

.header {
	padding: 20rpx 0;
	margin-bottom: 20rpx;
}

.title {
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
	color: #333;
}

.desc {
	font-size: 26rpx;
	color: #666;
}

.status-bar {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 30rpx;
	padding: 20rpx;
	background-color: #fff;
	border-radius: 12rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.status-step {
	display: flex;
	align-items: center;
	flex: 1;
}

.step-indicator {
	width: 60rpx;
	height: 60rpx;
	border-radius: 30rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-weight: bold;
	color: #fff;
	margin-right: 20rpx;
}

.drop-color {
	background-color: #1890ff;
}

.needle-color {
	background-color: #ff4d4f;
}

.step-text {
	font-size: 28rpx;
	color: #666;
}

.status-step.active .step-text {
	font-weight: bold;
	color: #333;
}

.status-step.completed .step-text {
	color: #52c41a;
}

.step-check {
	margin-left: 10rpx;
	color: #52c41a;
	font-weight: bold;
}

.step-connector {
	height: 2rpx;
	flex: 0.5;
	background-color: #e8e8e8;
	margin: 0 10rpx;
}

.selector-container {
	background-color: #fff;
	border-radius: 12rpx;
	padding: 10rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	height: 60vh;
	display: flex;
	justify-content: center;
	align-items: center;
}

.canvas-container {
	width: 100%;
	height: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
}

.instruction {
	display: flex;
	padding: 20rpx;
	background-color: #f0f9ff;
	border-radius: 12rpx;
	margin-bottom: 30rpx;
	border-left: 8rpx solid #1890ff;
}

.instruction-icon {
	font-size: 40rpx;
	margin-right: 20rpx;
}

.instruction-text {
	font-size: 26rpx;
	color: #333;
	line-height: 1.5;
}

.action-buttons {
	display: flex;
	gap: 20rpx;
	margin-top: auto;
	padding: 20rpx 0;
}

.action-btn {
	flex: 1;
	height: 80rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 40rpx;
	font-size: 28rpx;
	font-weight: bold;
}

.reset-btn {
	background-color: #f0f0f0;
	color: #666;
}

.next-btn {
	background-color: #1890ff;
	color: #fff;
}

.prev-btn {
	background-color: #f0f0f0;
	color: #666;
}

.confirm-btn {
	background-color: #52c41a;
	color: #fff;
}

.disabled-btn {
	opacity: 0.6;
}

.btn-text {
	font-size: 28rpx;
}

.selection-buttons {
	display: flex;
	gap: 20rpx;
	margin-bottom: 20rpx;
}

.selection-btn {
	flex: 1;
	height: 100rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background-color: #f5f5f5;
	border-radius: 12rpx;
	border: 2rpx solid #e8e8e8;
	padding: 10rpx;
}

.selection-btn.active {
	border: 2rpx solid #1890ff;
	background-color: #e6f7ff;
}

.selection-btn.completed {
	border-color: #52c41a;
}

.selection-btn.active.completed {
	border-color: #1890ff;
}

.btn-icon {
	font-size: 36rpx;
	margin-bottom: 6rpx;
}

.btn-text {
	font-size: 24rpx;
	color: #333;
}
</style> 